package org.bl.chat.controller;

import lombok.Cleanup;
import org.apache.catalina.User;
import org.bl.chat.common.dto.Response;
import org.bl.chat.service.UserService;
import org.bl.chat.util.IpUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Controller
public class ChatController {


    private final Path uploadDir = Paths.get("uploads");

    public ChatController() throws IOException {
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }
    }

    @PostMapping("/upload")
    @ResponseBody
    public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String filename = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        Path filePath = uploadDir.resolve(filename);
        @Cleanup
        InputStream inputStream = file.getInputStream();
        long copy = Files.copy(inputStream, filePath);
        // 返回上传文件的访问URL
        return "/files/" + filename;
    }

    @GetMapping("/files/{filename:.+}")
    public ResponseEntity<byte[]> serveFile( @PathVariable String filename,
                                             HttpServletRequest request ) throws IOException {
        Path file = uploadDir.resolve(filename);
        if (!Files.exists(file)) {
            return ResponseEntity.notFound().build();
        }

        byte[] bytes = Files.readAllBytes(file);

        // 根据文件扩展名设置Content-Type
        String mimeType = request.getServletContext().getMimeType(file.toString());
        if (mimeType == null) {
            mimeType = "application/octet-stream";
        }

        // 文件下载时，设置attachment响应头，如果是图片，浏览器会自动显示
        boolean isImage = mimeType.startsWith("image");

        // 编码文件名，防止中文乱码
        String encodedFilename = URLEncoder.encode(filename, String.valueOf(StandardCharsets.UTF_8)).replaceAll("\\+", "%20");

        // 使用 RFC 5987 标准方式设置 Content-Disposition
        String contentDisposition = (isImage ? "inline" : "attachment") +
                "; filename*=UTF-8''" + encodedFilename;

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(mimeType))
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
                .body(bytes);
    }
}
